#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 17:26
# @Author  : Tom_zc
# @FileName: prepare-label.py
# @Software: PyCharm
import os
import sys
import logging

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

from utils.gitcode_helper import GitCodeHelper
from utils.parse_params import parse_repo_info_by_webhook_payload
from utils.common import func_retry

_comment = "The pipeline(pipeline number:{}) is running. Please wait a moment... "


class PrePareLabelHelper:
    ci_running_labels = "ci-running"
    ci_labels = ["ci-failed", "ci-successful"]

    def __init__(self, owner, repo, pr_number, token):
        self.git_helper = GitCodeHelper(owner, repo, pr_number, token)
        self.pr_info = self.git_helper.get_pr()

    @func_retry()
    def delete_ci_labels(self):
        for label in self.pr_info["labels"]:
            if label["name"] in self.ci_labels:
                self.git_helper.delete_label(label["name"])

    @func_retry()
    def add_ci_run_labels(self):
        self.pr_info = self.git_helper.get_pr()
        labels = [i["name"] for i in self.pr_info["labels"]]
        if self.ci_running_labels not in labels:
            labels.append(self.ci_running_labels)
            self.git_helper.create_label(json_data=labels)


def main():
    token = os.getenv("gitcode_token")
    pipeline_number = os.getenv("PIPELINE_NUMBER")
    if not token or not pipeline_number:
        logging.info("Error:env git_code_token or PIPELINE_NUMBER must not be empty")
        sys.exit(-1)
    owner, repo, _, pr_number, _ = parse_repo_info_by_webhook_payload()
    prepare_label_helper = PrePareLabelHelper(owner, repo, pr_number, token)
    comment = _comment.format(pipeline_number)
    prepare_label_helper.git_helper.create_comment({"body": comment})
    prepare_label_helper.delete_ci_labels()
    prepare_label_helper.add_ci_run_labels()


if __name__ == '__main__':
    main()
